/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.robert.maps;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.andnav.osm.util.GeoPoint;
import org.andnav.osm.views.util.Util;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.app.Instrumentation.ActivityResult;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.SparseBooleanArray;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.robert.maps.R;
import com.robert.maps.utils.POI;
import com.robert.maps.utils.KmlPullParser;

/**
 * This example shows how to use choice mode on a list. This list is 
 * in CHOICE_MODE_MULTIPLE mode, which means the items behave like
 * checkboxes.
 */
public class KmlList extends Activity implements Runnable{
    
	private SQLiteDatabase mPOI;
	private ListView listView;
	private ArrayList<String> aKMLName;
	private Integer iCount=0;
	private SparseBooleanArray sA;
	private ArrayAdapter<String> aKMLArray;
	
	private KmlPullParser KmlParser;
	private ProgressDialog PDialog;
	private String sPOIName="";
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        View v = View.inflate(this, R.layout.kmllist , null);
        setContentView(v);
        
        listView = (ListView) v.findViewById(R.id.KmlListView);
        
		File folder = Util.getKmlFolder("Kml", true);
		if (folder.exists()) {
			File[] files = folder.listFiles();
			if (files != null){
				aKMLName = new ArrayList<String>(files.length);
				for (int i = 0; i < files.length; i++) {
					if (files[i].getName().toLowerCase().endsWith(".kml")) {
						aKMLName.add(files[i].getName()) ;
					}
				}
				aKMLArray = new ArrayAdapter<String>(this,
			            android.R.layout.simple_list_item_multiple_choice, aKMLName);
					//setListAdapter(aKMLArray);
				listView.setAdapter(aKMLArray);
		        listView.setItemsCanFocus(false);
		        listView.setTextFilterEnabled(true);
		        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
			}
		}
    }

  
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.kml_list_option_menu, menu);

		return true;
	}
    
    @Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		

		if (sA != null){sA = null;}
		
		if (listView!= null && listView.getCount()>0) {
			sA = listView.getCheckedItemPositions();
		}
		
		switch (item.getItemId()) {
		case (R.id.list_import_kml):
			if (sA!=null && sA.size()>0){
				PDialog = ProgressDialog.show(this,null, "Please wait while importing...", true, true);
				Thread thread = new Thread(this);
		        thread.start();
			}
			return true;
		}
		return true;
    }
    
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        	PDialog.setMessage("Importing " + sPOIName);
        }
    };
    
    public void run() {
        ImportKML();
        PDialog.dismiss();
        setResult(30001);  
    }

	private void ImportKML() {
		for (int i = 0; i < sA.size(); i++) {
			if (sA.get(sA.keyAt(i))){
				KmlParser = new KmlPullParser("/sdcard/rmaps/kml/" +aKMLName.get(sA.keyAt(i)));
				if (mPOI == null)
		    	{
		    		this.mPOI= Util.getPOIDatabase(false);
		    	}
				String newPlaceID="";
				List<POI> newPOIList = KmlParser.parse();
				for (int j = 0; j < newPOIList.size(); j++) {

					final Cursor c = this.mPOI.rawQuery("select a.* from PlacesInfo a inner join PlacesGeoPoint b " +
							"on a.PlaceID = b.PlaceID where (a.name = '" + newPOIList.get(j).getName() + 
							"' or (b.Latitude= " + ((GeoPoint) newPOIList.get(j).getGeoPoint().get(0)).getLatitudeE6() +
							" and b.Longitude= " + ((GeoPoint) newPOIList.get(j).getGeoPoint().get(0)).getLongitudeE6() +" ))", null);
					if (c.getCount()>0){
						c.close();
						continue; //new record already exist
					}
					c.close();
					sPOIName = newPOIList.get(j).getName();
					handler.sendEmptyMessage(0);
					final ContentValues cv = new ContentValues();
					cv.put("name", newPOIList.get(j).getName());
					cv.put("description", newPOIList.get(j).getDescription());
					//cv.put("latitude", newPOIList.get(j).getGeoPoint().getLatitudeE6());
					//cv.put("longitude", newPOIList.get(j).getGeoPoint().getLongitudeE6());
					cv.put("category", newPOIList.get(j).getGeoPoint().size() > 1 ? "Path" : "Imported");
					cv.put("show", true);
					cv.put("city", "Default");
					this.mPOI.insert("PlacesInfo", null, cv);
					
					final Cursor c1 = this.mPOI.rawQuery("select last_insert_rowid()", null);
					if (c1.moveToFirst())
						newPlaceID = c1.getString(0);
					c1.close();
					for (int k = 0; k< newPOIList.get(j).getGeoPoint().size(); k ++){
						this.mPOI.execSQL("Insert into PlacesGeoPoint values('" + newPlaceID + 
								"','" + ((GeoPoint) newPOIList.get(j).getGeoPoint().get(k)).getLatitudeE6() + 
								"','" + ((GeoPoint) newPOIList.get(j).getGeoPoint().get(k)).getLongitudeE6() + "')");
					}
				}
			}
		}
	}
    
    
}
